import os
import pandas as pd
from config import SEARCH_KEYWORDS, FILTER_KEYWORDS, SCREENSHOT_DIR, CSV_OUTPUT
from screenshot_helper import take_screenshot, ensure_screenshot_dir
from qq_automation import search_keyword, get_chat_records, filter_records
import time
import pygetwindow
import pyautogui
import pyperclip

def first_run_setup():
    print("首次运行，请依次截图：QQ主窗口、顶部搜索框、群列表、聊天记录区域。")
    ensure_screenshot_dir(SCREENSHOT_DIR)
    # 示例：截图顶部搜索框
    input("请将鼠标移动到QQ顶部搜索框，按回车截图...")
    take_screenshot(os.path.join(SCREENSHOT_DIR, "search_box.png"))
    # 可继续添加其他截图
    print("截图完成。后续将自动运行。")

def ensure_qq_active():
    # 获取所有窗口标题包含“QQ”的窗口
    windows = [w for w in pygetwindow.getAllWindows() if "QQ" in w.title]
    if windows:
        win = windows[0]
        win.activate()
        time.sleep(0.5)
        return True
    else:
        print("未找到QQ窗口，请确保QQ已打开。")
        return False

def locate_and_click(image_path, confidence=0.8):
    """
    在屏幕上查找并点击指定图片。
    :param image_path: 图片路径
    :param confidence: 匹配置信度
    :return: 是否找到并点击成功
    """
    try:
        # 使用 pyautogui.locateOnScreen 查找图片
        # 如果找到，则点击其中心点
        location = pyautogui.locateOnScreen(image_path, confidence=confidence)
        if location:
            center_x = location.left + location.width / 2
            center_y = location.top + location.height / 2
            pyautogui.click(center_x, center_y)
            return True
        else:
            print(f"未找到图片: {image_path}")
            return False
    except Exception as e:
        print(f"查找图片失败:  {image_path} ,{e}")
        return False

def close_recent_windows(times=2):
    """
    关闭群搜索，群聊天，也就是最近打开的两个
    """
    for _ in range(times):
        pyautogui.hotkey('ctrl', 'w')
        time.sleep(2)

def scroll_group_list():
    """
    尝试向下滚动群列表，以加载更多群。
    :return: 是否成功滚动
    """
    try:
        # 尝试向下滚动
        pyautogui.scroll(-100) # 向下滚动
        time.sleep(0.5) # 等待加载
        return True
    except Exception as e:
        print(f"滚动失败: {e}")
        return False

def find_all_group_positions():
    """
    查找所有群的左上角坐标。
    :return: 群左上角坐标的列表
    """
    group_positions = []
    try:
        # 尝试查找群列表的左上角
        location = pyautogui.locateOnScreen(os.path.join(SCREENSHOT_DIR, "group_list_top.png"), confidence=0.8)
        if location:
            group_positions.append((location.left, location.top))
            print(f"找到群列表左上角: {location.left}, {location.top}")

        # 尝试查找群列表的右上角
        location = pyautogui.locateOnScreen(os.path.join(SCREENSHOT_DIR, "group_list_top.png"), confidence=0.8, region=(0, 0, 100, 100)) # 在屏幕左上角附近查找
        if location:
            group_positions.append((location.left, location.top))
            print(f"找到群列表右上角: {location.left}, {location.top}")

        # 尝试查找群列表的左下角
        location = pyautogui.locateOnScreen(os.path.join(SCREENSHOT_DIR, "group_list_bottom.png"), confidence=0.8)
        if location:
            group_positions.append((location.left, location.top))
            print(f"找到群列表左下角: {location.left}, {location.top}")

        # 尝试查找群列表的右下角
        location = pyautogui.locateOnScreen(os.path.join(SCREENSHOT_DIR, "group_list_bottom.png"), confidence=0.8, region=(0, 0, 100, 100)) # 在屏幕左上角附近查找
        if location:
            group_positions.append((location.left, location.top))
            print(f"找到群列表右下角: {location.left}, {location.top}")

        return group_positions
    except Exception as e:
        print(f"查找群位置失败: {e}")
        return []

def click_group_more_link():
    img_path = os.path.join(SCREENSHOT_DIR, "chat_reocrd_more.png")
    location = pyautogui.locateOnScreen(img_path, confidence=0.7)
    if location:
        # 计算“更多”链接的中心点坐标（右移80像素，可根据实际调整）
        more_x = location.left + location.width - 50
        more_y = location.top + location.height // 2
        pyautogui.click(more_x, more_y)
        print(f"已点击更多链接 {more_x}, {more_y}")
        return True
    else:
        print("未找到 chat_record_more")
        return False

def safe_locate_on_screen(image_path, confidence=0.8):
    import pyautogui
    try:
        return pyautogui.locateOnScreen(image_path, confidence=confidence)
    except pyautogui.ImageNotFoundException:
        return None
 # 用坐标规律依次点击每个群
def click_all_groups_by_row(start_x, start_y, row_height, group_count, all_results):
    for i in range(group_count):
        y = start_y + i * row_height
        pyautogui.click(start_x, y)
        time.sleep(2)
        # 后续操作...
        # 点击聊天记录按钮
        if locate_and_click(os.path.join(SCREENSHOT_DIR, "chat_record.png"), confidence=0.8):
            time.sleep(1)
            records = get_chat_records()
            filtered = filter_records(records)
            for rec in filtered:
                all_results.append({"content": rec})
            print("关闭打开的群聊界面及对应的聊天记录界面")    
            time.sleep(5)

def activate_chat_record_window():
    for w in pygetwindow.getAllWindows():
        print(w.title)
        if "本地搜索" in w.title:
            w.activate()
            time.sleep(0.5)
            return True
    print("未找到聊天记录主窗体")
    return False

def main():
    if not ensure_qq_active():
        print("未能激活QQ窗口，请手动切换到QQ后重试。")
        return
    if not os.path.exists(SCREENSHOT_DIR) or not os.listdir(SCREENSHOT_DIR):
        first_run_setup()

    all_results = []

    # 只用第一个关键字进行搜索
    if SEARCH_KEYWORDS:
        keyword = SEARCH_KEYWORDS[0]
        print(f"正在搜索: {keyword}")
        if search_keyword(keyword):
            time.sleep(1)
            # 查找并点击“更多”按钮
            if click_group_more_link():
                time.sleep(2)
                                
                img_path = os.path.join(SCREENSHOT_DIR, "chat_record_search.png")
                location = pyautogui.locateOnScreen(img_path, confidence=0.8)       
                if location:
                    # 单个群聊区域位置
                    more_x = location.left + location.width / 2 - 300
                    more_y = location.top + location.height + 300
                    print(f"单个群聊 {more_x}, {more_y}")

                    # 获取查询框的相对位置（假设查询框在聊天记录区域上方偏移）
                    query_box_x = location.left + location.width / 2
                    query_box_y = location.top + 70  # 可根据实际调整
    
                    # 选中搜索框
                    pyautogui.click(query_box_x, query_box_y)
                    time.sleep(0.5)
                    
                    for keyword in SEARCH_KEYWORDS:
                        # 每次循环输入关键字前，激活“聊天记录”主窗体。
                        activate_chat_record_window()
                        # 关键：每次都点击搜索框，确保焦点
                        pyautogui.click(query_box_x, query_box_y)
                        time.sleep(0.3)
                        print(f"正在搜索: {keyword}")
                        # 点击查询框，输入关键字
                        time.sleep(0.5)
                        pyautogui.hotkey('ctrl', 'a')
                        pyautogui.press('backspace')
                        pyperclip.copy(keyword)
                        pyautogui.hotkey('ctrl', 'v')
                        pyautogui.press('enter')
                        time.sleep(2)
                        click_all_groups_by_row(more_x, more_y, 60, 10, all_results)

                        
    if all_results:
        df = pd.DataFrame(all_results)
        df.to_csv(CSV_OUTPUT, index=False, encoding='utf-8-sig')
        print(f"已保存到 {CSV_OUTPUT}")
    else:
        print("未找到符合条件的聊天记录。")

if __name__ == "__main__":
    main() 